package problem47;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//47.全排列2
//https://leetcode.cn/problems/permutations-ii/

class Solution {
    List<List<Integer>> ret = new ArrayList<>();
    List<Integer> list = new ArrayList<>();
    boolean[] st;
    public List<List<Integer>> permuteUnique(int[] nums) {
        st = new boolean[nums.length];
        Arrays.sort(nums);
        dfs(nums, 0);
        return ret;
    }
    public void dfs(int[] nums, int u) {
        if(u == nums.length) {
            ret.add(new ArrayList(list));
            return;
        }

        for(int i = 0; i<nums.length; i++) {
            //选
            if(!st[i]) {
                if(i > 0 && !st[i-1] && nums[i] == nums[i-1]) 
                    continue;
                    
                list.add(nums[i]);
                st[i] = true;
                dfs(nums, u+1);
                list.remove(list.size()-1);
                st[i] = false;
            }
        }
    }
}